#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
生成 uni-app tabbar 图标
直接使用 PIL 生成 PNG 图标，无需 SVG 转换
"""

import os
import sys
from pathlib import Path

try:
    from PIL import Image, ImageDraw, ImageFont
except ImportError:
    print("正在安装 Pillow...")
    os.system(f"{sys.executable} -m pip install Pillow -i https://pypi.tuna.tsinghua.edu.cn/simple")
    from PIL import Image, ImageDraw, ImageFont

# 图标配置
ICON_SIZE = 81  # uni-app tabbar 图标推荐尺寸
NORMAL_COLOR = "#7A7E83"  # 未选中颜色
ACTIVE_COLOR = "#007AFF"  # 选中颜色


def hex_to_rgb(hex_color):
    """将十六进制颜色转换为 RGB"""
    hex_color = hex_color.lstrip('#')
    return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))


def draw_home_icon(draw, size, color):
    """绘制首页图标（房子）"""
    center_x, center_y = size // 2, size // 2
    # 房子的主体
    house_points = [
        (center_x, center_y - 20),  # 顶部
        (center_x - 15, center_y - 5),  # 左上
        (center_x - 15, center_y + 15),  # 左下
        (center_x + 15, center_y + 15),  # 右下
        (center_x + 15, center_y - 5),  # 右上
    ]
    draw.polygon(house_points, fill=color, outline=color, width=2)
    # 门
    door_rect = [
        center_x - 6, center_y + 2,
        center_x + 6, center_y + 15
    ]
    draw.rectangle(door_rect, fill=(255, 255, 255), outline=color, width=1)


def draw_favorite_icon(draw, size, color):
    """绘制收藏图标（心形）"""
    center_x, center_y = size // 2, size // 2
    
    # 绘制心形
    # 左侧半圆
    draw.ellipse([center_x - 12, center_y - 8, center_x - 2, center_y + 2], 
                 fill=color, outline=color)
    # 右侧半圆
    draw.ellipse([center_x + 2, center_y - 8, center_x + 12, center_y + 2], 
                 fill=color, outline=color)
    # 下方三角形
    triangle_points = [
        (center_x, center_y + 8),  # 底部
        (center_x - 12, center_y - 2),  # 左上
        (center_x + 12, center_y - 2),  # 右上
    ]
    draw.polygon(triangle_points, fill=color, outline=color)


def draw_profile_icon(draw, size, color):
    """绘制个人中心图标（用户）"""
    center_x, center_y = size // 2, size // 2
    
    # 头部（圆形）
    head_radius = 8
    draw.ellipse([
        center_x - head_radius, center_y - 12,
        center_x + head_radius, center_y + 4
    ], fill=color, outline=color, width=2)
    
    # 身体（扇形/梯形）
    body_points = [
        (center_x - 12, center_y + 4),  # 左上
        (center_x + 12, center_y + 4),  # 右上
        (center_x + 10, center_y + 20),  # 右下
        (center_x - 10, center_y + 20),  # 左下
    ]
    draw.polygon(body_points, fill=color, outline=color, width=2)


def create_icon(icon_type, color, output_path):
    """创建图标"""
    # 创建透明背景的图片
    img = Image.new('RGBA', (ICON_SIZE, ICON_SIZE), (255, 255, 255, 0))
    draw = ImageDraw.Draw(img)
    
    # 转换为 RGB 颜色
    rgb_color = hex_to_rgb(color)
    
    # 根据类型绘制不同的图标
    if icon_type == 'home':
        draw_home_icon(draw, ICON_SIZE, rgb_color)
    elif icon_type == 'favorite':
        draw_favorite_icon(draw, ICON_SIZE, rgb_color)
    elif icon_type == 'profile':
        draw_profile_icon(draw, ICON_SIZE, rgb_color)
    else:
        raise ValueError(f"未知的图标类型: {icon_type}")
    
    # 保存图片
    img.save(output_path, 'PNG')
    print(f"✓ 生成成功: {output_path}")


def generate_icons():
    """生成所有 tabbar 图标"""
    # 确定输出目录
    script_dir = Path(__file__).parent.absolute()
    project_root = script_dir.parent
    tabbar_dir = project_root / 'src' / 'static' / 'tabbar'
    
    # 确保目录存在
    tabbar_dir.mkdir(parents=True, exist_ok=True)
    
    print(f"图标输出目录: {tabbar_dir}")
    print("-" * 50)
    
    icons = ['home', 'favorite', 'profile']
    
    for icon_type in icons:
        # 生成普通状态图标
        normal_path = tabbar_dir / f"{icon_type}.png"
        create_icon(icon_type, NORMAL_COLOR, normal_path)
        
        # 生成激活状态图标
        active_path = tabbar_dir / f"{icon_type}-active.png"
        create_icon(icon_type, ACTIVE_COLOR, active_path)
    
    print("-" * 50)
    print("完成! 所有图标已生成")
    print("\n生成的图标文件:")
    for icon_type in icons:
        print(f"  - {icon_type}.png")
        print(f"  - {icon_type}-active.png")


if __name__ == '__main__':
    print("=" * 50)
    print("uni-app TabBar 图标生成工具")
    print("=" * 50)
    print()
    
    try:
        generate_icons()
        print("\n✓ 所有图标生成完成!")
    except KeyboardInterrupt:
        print("\n\n用户中断操作")
        sys.exit(1)
    except Exception as e:
        print(f"\n错误: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)
